package k3.utils 
{
	import k3.event.KEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * ...
	 * @author FireKnight
	 */
	public class MyTimer extends EventDispatcher
	{
		private var timer:Timer;
		private var repeatCount:uint;
		private var delay:uint;
		private var count:uint=0;
		private var callBack:Function;
		public const TIME_COMPLETE:String="timer_complete";
		public function MyTimer(f:Function,_delay:Number=1,_repeat:uint=0,flag:String="") 
		{
			callBack = f;
			delay = _delay*1000;
			if(flag.length>0)
			{
				trace("MyTimer flag is "+ flag);
			}
			repeatCount = _repeat;
			addTimer();
		}
		
		private function removeTimer():void
		{
			if (timer)
			{
				stop();
				if (timer.hasEventListener(TimerEvent.TIMER))
				{
					timer.removeEventListener(TimerEvent.TIMER, handleTimerFuncton);
					timer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.handleTimeOver);
				}
				timer = null;
				count=0;
			}
			
		}
		
		public function get currentCount():uint
		{
			return count;
		}
		
		private function addTimer():void
		{
			removeTimer();
			timer = new Timer(delay, repeatCount);
			timer.addEventListener(TimerEvent.TIMER, handleTimerFuncton, false, 0, true);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE,this.handleTimeOver,false,0,true);
		}
		
		public function stop():void
		{
			if (timer)
			{
				if (timer.running)
				{
					timer.stop();
				}
			}
		}
		
		public function start():void
		{
			if(!timer.running)
			{
				timer.start();
			}
			//trace("timer.currentCount="+timer.currentCount);
			
		}
		
		
		public function rest():void
		{
			count=0;
			timer.reset();
		}
		
		public function GC():void
		{
			removeTimer();
		}
		
		private function handleTimeOver(e:TimerEvent):void
		{
			trace("timeover");
			this.dispatchEvent(new KEvent(TIME_COMPLETE));
		}
		
		private function handleTimerFuncton(e:TimerEvent):void
		{
			count++;
			callBack();
		}
		
	}

}